import React from "react";
import styles from "./index.style";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRoute } from "@react-navigation/native";
import { QrScanResult } from "@/components/QRCode/ScanPage";
import {
  View,
  Text,
  Alert,
  TouchableOpacity,
  Image,
  ImageStyle,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import {ResponseCode} from "@/types/api-common";
import {loginByQrCodeApi} from "@/services/api/login";
import {getDeviceTypeImage, getDeviceTypeLabel} from "@/utils/device-utils";

// 二维码类型
enum QrCodeType {
  LOGIN = 0, // 登录二维码
}

// 二维码状态
enum QrCodeStatus {
  PENDING = 0, // 待扫描
  SCANNED = 1, // 已扫描
  EXPIRED = 2, // 已过期
}

export default function ScanResult() {
  const { result } = useRoute().params as { result: string };
  const scanResult: QrScanResult = JSON.parse(decodeURIComponent(result));
  const router = useRouter();

  const handleLogin = async () => {
    const resp = await loginByQrCodeApi(scanResult.qrId);
    if (resp.data.code === ResponseCode.SUCCESS) {
      console.log(resp.data);
      if (router.canGoBack) {
        router.back();
      }
    } else {
      console.error("登录失败:", resp.data);
      Alert.alert("登录失败", resp.data.message || "请稍后再试");
    }
  };

  const handleReject = () => {
    if (router.canGoBack) {
      router.back();
    }
  };

  if (
    scanResult.type === QrCodeType.LOGIN &&
    scanResult.status === QrCodeStatus.PENDING
  ) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>登录确认</Text>
          <TouchableOpacity
            onPress={() => {
              if (router.canGoBack) router.back();
            }}
            style={styles.closeButton}
          >
            <Ionicons name="close" size={28} color="#333" />
          </TouchableOpacity>
        </View>
        <View style={styles.card}>
          <View style={styles.iconWrapper}>
            <Image
              source={getDeviceTypeImage(scanResult.device.deviceType)}
              style={styles.imageBackground as ImageStyle}
            />
          </View>
          <Text style={styles.appTitle}>
            登录 {getDeviceTypeLabel(scanResult.device.deviceType)} 闪聊
          </Text>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>登录地点：</Text>
            <Text style={styles.infoValue}>{scanResult.location}</Text>
          </View>
          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>设备名称：</Text>
            <Text style={styles.infoValue}>{scanResult.device.deviceName}</Text>
          </View>

          <Text style={styles.warning}>
            请确认该设备在你身边并且是你本人登录，不是本人登录可能会导致你的账号或者资金被盗。
          </Text>

          <View style={styles.buttonGroup}>
            <TouchableOpacity style={styles.loginButton} onPress={handleLogin}>
              <Text style={styles.loginText}>登录</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.rejectButton}
              onPress={handleReject}
            >
              <Text style={styles.rejectText}>拒绝</Text>
            </TouchableOpacity>
          </View>
        </View>
      </SafeAreaView>
    );
  } else if (
    scanResult.type === QrCodeType.LOGIN &&
    scanResult.status === QrCodeStatus.EXPIRED
  ) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>二维码已过期</Text>
          <TouchableOpacity
            onPress={() => {
              if (router.canGoBack) router.back();
            }}
            style={styles.closeButton}
          >
            <Ionicons name="close" size={28} color="#333" />
          </TouchableOpacity>
        </View>
        <View style={styles.card}>
          <Text style={styles.appTitle}>二维码已过期，请重新生成二维码</Text>
        </View>
      </SafeAreaView>
    );
  } else if (
    scanResult.type === QrCodeType.LOGIN &&
    scanResult.status === QrCodeStatus.SCANNED
  ) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>已确认登录</Text>
          <TouchableOpacity
            onPress={() => {
              if (router.canGoBack) router.back();
            }}
            style={styles.closeButton}
          >
            <Ionicons name="close" size={28} color="#333" />
          </TouchableOpacity>
        </View>
        <View style={styles.card}>
          <Text style={styles.appTitle}>该二维码已被使用，请勿重复操作</Text>
        </View>
      </SafeAreaView>
    );
  } else {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>无法识别二维码</Text>
          <TouchableOpacity
            onPress={() => {
              if (router.canGoBack) router.back();
            }}
            style={styles.closeButton}
          >
            <Ionicons name="close" size={28} color="#333" />
          </TouchableOpacity>
        </View>
        <View style={styles.card}>
          <Text style={styles.appTitle}>二维码内容无法识别或不支持</Text>
        </View>
      </SafeAreaView>
    );
  }
}
